package com.mlamp.二叉树;

import sun.reflect.generics.tree.Tree;

import java.util.LinkedList;
import java.util.Queue;

public class 树的子结构 {

    public static void main(String[] args) {
        树的子结构 instance = new 树的子结构();
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2);
        root.right = new TreeNode(7);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(9);

        TreeNode root2 = new TreeNode(4);
        root2.left = new TreeNode(2);
        root2.right = new TreeNode(7);

        boolean subTree = instance.isSubTree(root, root2);
        System.out.println(subTree);


    }

    public boolean isSubTree(TreeNode root1, TreeNode root2) {
        if (root1 == null || root2 == null) return false;
        boolean res = false;
        if (root1.value == root2.value) res = helper(root1, root2);
        if (!res) res = isSubTree(root1.left, root2);
        if (!res) res = isSubTree(root2.right, root2);
        return res;
    }


    public boolean helper(TreeNode root1, TreeNode root2) {
        if (root2 == null) return true;
        if (root1 == null) return false;
        if (root1.value != root2.value) return false;
        return helper(root1.left, root2.left) && helper(root1.right, root2.right);
    }

    public static class TreeNode {
        int value;
        TreeNode left;
        TreeNode right;

        public TreeNode(int value) {
            this.value = value;
        }
    }


    public void printTree(TreeNode root) {
        if (root == null) return;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left != null) queue.offer(poll.left);
                if (poll.right != null) queue.offer(poll.right);
                sb.append(poll.value).append(" ");
            }
            System.out.println(sb.toString());
        }
    }
}
